package com.djpeng.du.simple_pinyin;

import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * Created by dujp on 15/5/2.
 * djpeng.du@gmail.com
 */
public class ResourceHelper {
    private static String cn_to_py_file = "/py.txt";

    public static Table readResource() throws Exception{
        Table table = new Table();
        BufferedReader reader;
        reader = new BufferedReader(new InputStreamReader(ResourceHelper.class.getResourceAsStream(cn_to_py_file)));
        String line;
        while ((line = reader.readLine())!=null){
            String[] kv = line.split(" ");
            String key = kv[0];
            String[] vs = kv[1].substring(1, kv[1].length()-1).split(",");
            table.setKey(key, vs);
        }
        return table;
    }

    public static Table readResource(Map<String, List<String>> resource){
        Table table = new Table(resource.size());
        for(Map.Entry<String, List<String>> entry:resource.entrySet()){
            table.setKey(entry.getKey(), entry.getValue().toArray(new String[entry.getValue().size()]));
        }
        return table;
    }

    public static Table readResource(String file, Analyzer analyzer) throws Exception{
        Table table = new Table();
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        String line;
        while((line=reader.readLine())!=null){
            List<String> kv = analyzer.split(line);
            String key = kv.get(0);
            List<String> strings = kv.subList(1, kv.size());
            String[] value = strings.toArray(new String[strings.size()]);
            table.setKey(key, value);
        }
        return table;
    }

    interface Analyzer{
        List<String> split(String line);
    }
}
